const $ = {};
const settings = require('../models/settings.json');
const Core = require('@alicloud/pop-core');
const { parsePhoneNumberFromString } = require('libphonenumber-js');
const cryptoRandomString = require('crypto-random-string');
const Vcode = require('../models/vcode').Vcode;

var isPro = require('../libs/debug').isPro;
var isDev = require('../libs/debug').isDev;
var isDbg = require('../libs/debug').isDbg;

const client = new Core({
    accessKeyId: settings.alicloud.accessKeyId,
    accessKeySecret: settings.alicloud.accessKeySecret,
    endpoint: 'https://dysmsapi.aliyuncs.com',
    apiVersion: '2017-05-25'
});

$.check = async function (phone, code) {
    const vcode = await Vcode.findOneAndDelete({phone, code}).exec();
    return !!vcode;
};

$.send = async function (phone) {
    const smsConfig = settings.alicloud.sms;

    if (/^19999\d{6}$/.test(phone)) {  // for testing
      const code = '000000';
      await Vcode.create({phone, code});
      return true;
    }

    const parsedPhone = parsePhoneNumberFromString(phone, 'CN');
    if (!parsedPhone.isValid()) {
        return false;
    }
    const phoneNumber = parsedPhone.nationalNumber;
    const code = generateVerificationCode();

    const sendParams = {
        PhoneNumbers: phoneNumber,
        SignName: smsConfig.signName,
        TemplateCode: smsConfig.templateCode,
        TemplateParam: JSON.stringify({code}),
    };

    await Vcode.create({phone, code});

    return !!await client.request('SendSms', sendParams, { method: 'POST' });
};

function generateVerificationCode () {
    return cryptoRandomString({length: 6, characters: '1234567890'});
}

module.exports = $;
